﻿/*-----------------------------------/
/* Create By.Ben 20181206
/*----------------------------------*/
var userDetailFormVue = new Vue({
    el: "#userDetailForm",
    data: {
        isNewUser: true,        //判断是否新用户
        user: {                 //用户信息
            ID: 0,
            Name: "",
            NameChs: "",
            Password: "",
            Email: "",
            Mobile: ""
        },
        groupList: [],
        roleList: [],
        permissionList: []
    },
    methods: {
        SaveUser: function (event) {
            event.preventDefault();
            SaveUserDetail(this);
        },
        UpdateUser: function (event) {
            event.preventDefault();
            UpdateUserDetail(this);
        },
        ListGroup: function (event) {
            ListAllGroup(this);
        },
        UpdateGroup: function (event) {
            event.preventDefault();
            ResetUserGroupMapping(this);
            UpdateUserDetail(this);
        },
        ListRole: function (event) {
            ListAllRole(this);
        },
        UpdateRole: function (event) {
            event.preventDefault();
            ResetUserRoleMapping(this);
            UpdateUserDetail(this);
        },
        ListPermission: function (event) {
            ListAllPermission(this);
        },
        UpdatePermission: function (event) {
            event.preventDefault();
            ResetUserPermissionMapping(this);
            UpdateUserDetail(this);
        }
    },
    created: function () {
        //页面加载前初始的数据
        InitialAztechScript();
    },
    mounted: function () {
        //页面加载后初始的数据
        var isNew = GetQueryString("IsNew");
        var userID = GetQueryString("UserID");
        
        if (isNew == "true") {
            this.isNewUser = true;
        } else {
            if (userID == null || userID.length == 0) {
                userID = GlobalUser.getUserInfo().ID;
            }
            this.isNewUser = false;
            GetUserDeatil(this, userID);
        } 
    },
    watch: {
        user: {
            handler: function (val, oldVal) {
                if (val.Name.length > 0)
                    CheckUsername(this);
                if (val.isNewUser && val.Password.length > 0)
                    CheckPassword(this);
                if (!val.isNewUser && val.Password)
                    CheckPassword(this);
                if (val.NameChs.length > 0)
                    CheckUsernameChs(this);
                if (val.Email.length > 0)
                    CheckEmail(this);
                if (val.Mobile.length > 0)
                    CheckMobile(this);
            },
            deep: true
        }
    }
})

/**
 * 获取用户信息,用于编辑用户
 */
function GetUserDeatil(vue, userID) {
    parent.ShowAzLoading();
    $.ajax({
        type: "GET",
        url: "/Account/GetUserByID?UserID=" + userID + "&v=" + Math.random(),
        success: function (res) {
            if (res.status == "Success") {
                vue.user = res.data;
            } else {
                toastr.error(res.message);
            }  
            //SetUserDetail(vue, res.data);
            parent.HideAzLoading();
        },
        error: function (err) {
            console.log(err);
            parent.HideAzLoading();
            toastr.error("获取用户信息失败，请稍候再试Failed to get user information. Please try again later。");
        }
    });
}

/**
 * 增加用户信息
 */
function SaveUserDetail(vue) {
    if (CheckUser(vue)) {
        parent.ShowAzLoading();
        $("button").attr("disabled", true);
        $.ajax({
            type: "POST",
            url: "/Account/SaveUser",
            data: { user: vue.user },
            success: function (res) {
                if (res.status == "Success") {
                    toastr.success("创建用户成功User created successfully。");
                    ResetForm(vue);
                } else {
                    toastr.error(res.message);
                }
            },
            error: function (err) {
                console.log(err);
                toastr.error("系统发生内部错误，请更换浏览器或稍后重试An internal error occurred in the system. Please change your browser or try again later。");
            },
            complete: function () {
                parent.HideAzLoading();
                $("button").removeAttr("disabled");
            }
        })
    }
}

/**
 * 更新用户信息
 */
function UpdateUserDetail(vue) {
    if (CheckUser(vue)) {
        parent.ShowAzLoading();
        $("button").attr("disabled", true);
        $.ajax({
            type: "POST",
            url: "/Account/UpdateUser",
            data: { user: vue.user },
            success: function (res) {
                if (res.status == "Success") {
                    toastr.success("更新用户成功User updated successfully。");
                } else {
                    toastr.error(res.message);
                }
            },
            error: function (err) {
                console.log(err);
                toastr.error("系统发生内部错误，请更换浏览器或稍后重试An internal error occurred in the system. Please change your browser or try again later。");
            },
            complete: function () {
                parent.HideAzLoading();
                $("button").removeAttr("disabled");
            }
        })
    }
}


/*校验用户信息 */
function CheckUser(vue) {
    if (!CheckUsername(vue)) {
        toastr.error("请填写正确用户名Please fill in the correct user name。");
        return false;
    } else if (!CheckPassword(vue)) {
        toastr.error("请填写正确密码Please fill in the correct password。");
        return false;
    } else if (!CheckUsernameChs(vue)) {
        toastr.error("请填写中文名Please fill in your Chinese name。");
        return false;
    } else if (!CheckEmail(vue)) {
        toastr.error("请填写正确邮箱Please fill in the correct email address。");
        return false;
    } else if (!CheckMobile(vue)) {
        toastr.error("请填写正确电话号码Please fill in the correct telephone number。");
        return false;
    } else {
        return true;
    }
}


/*校验用户名是否合法 */
function CheckUsername(vue) {
    var reg = /^[A-Za-z0-9.]{2,20}$/;
    var result = reg.test(vue.user.Name);

    $("#username").removeClass("has-error");    
    if (!result) {
        $("#username").addClass("has-error");    
    }
    return result;
}

/*校验用户中文是否合法 */
function CheckUsernameChs(vue) {
    var reg = /^[A-Za-z0-9.\u4e00-\u9fa5]{2,20}$/;
    var result = reg.test(vue.user.NameChs);
    
    $("#usernameChs").removeClass("has-error");
    if (!result) {
        $("#usernameChs").addClass("has-error");
    }
    return result;
}

/*校验密码是否合法 */
function CheckPassword(vue) {
    var reg = /^[A-Za-z0-9]{4,12}$/;
    var result = reg.test(vue.user.Password);

    //如果不是新用户，不填写密码则不检查
    if (!vue.isNewUser) {
        if (vue.user.Password == null || vue.user.Password.length == 0)
            result = true;
    }
        
    $("#password").removeClass("has-error");
    if (!result) {
        $("#password").addClass("has-error");
    }
    return result;
}

/*校验邮件地址是否合法 */
function CheckEmail(vue) {
    var reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
    var result = reg.test(vue.user.Email);

    $("#email").removeClass("has-error");
    if (!result) {
        $("#email").addClass("has-error");
    }
    return result;
}

/*校验电话号码是否合法 */
function CheckMobile(vue) {
    var reg = /^[0-9]*$/;
    var result = reg.test(vue.user.Mobile);

    $("#mobile").removeClass("has-error");
    if (!result) {
        $("#mobile").addClass("has-error");
    }
    return result;
}

/**
 *清空表单信息
 */
function ResetForm(vue) {
    vue.user = {               
        ID: 0,
        Name: "",
        NameChs: "",
        Password: "",
        Email: "",
        Mobile: ""
    };
}

/**
 * 列出所有用户组信息
 */
function ListAllGroup(vue) {
    parent.ShowAzLoading();
    $.ajax({
        type: "GET",
        url: "/Account/ListGroup?v=" + Math.random(),
        success: function (res) {
            if (res.status == "Success") {
                vue.groupList = res.data;

                vue.$nextTick(function () {
                    //监听Bootstrap中Tab元素显示事件
                    $('a[data-toggle="tab"]').off('shown.bs.tab').on('shown.bs.tab', function (e) {
                        parent.ResizeAzModal();
                        //选中已有用户组关系记录
                        $("#userGroupDetail").find("input[type=checkbox]").each(function () {
                            for (var idx in vue.user.UserGroupMappings) {
                                if (vue.user.UserGroupMappings[idx].GroupID == $(this).val()) {
                                    $(this).prop("checked", true);
                                }
                            }
                        });
                    });
                })
            } else {
                toastr.error(res.message);
            }
            parent.HideAzLoading();
        },
        error: function (err) {
            console.log(err);
            parent.HideAzLoading();
            toastr.error("服务器发生错误，请稍候再试An error occurred in the server. Please try again later。");
        }
    });
}

/**
 * 重置用户所属组关系信息
 */
function ResetUserGroupMapping(vue) {
    if (vue.user != null) {
        vue.user.UserGroupMappings = [];
        $("#userGroupDetail").find("input[type=checkbox]").each(function () {
            if ($(this).prop("checked") == true) {
                var mapping = {
                    GroupID: $(this).val(),
                    UserID: vue.user.ID
                }
                vue.user.UserGroupMappings.push(mapping);
            }
        });
    }   
}

/**
 * 列出所有用户角色信息
 */
function ListAllRole(vue) {
    parent.ShowAzLoading();
    $.ajax({
        type: "GET",
        url: "/Account/ListRole?v=" + Math.random(),
        success: function (res) {
            if (res.status == "Success") {
                vue.roleList = res.data;

                vue.$nextTick(function () {
                    //监听Bootstrap中Tab元素显示事件
                    $('a[data-toggle="tab"]').on('shown.bs.tab').on('shown.bs.tab', function (e) {
                        parent.ResizeAzModal();
                        //选中已有角色关系记录
                        $("#userRoleDetail").find("input[type=checkbox]").each(function () {
                            for (var idx in vue.user.UserRoleMappings) {
                                if (vue.user.UserRoleMappings[idx].RoleID == $(this).val()) {
                                    $(this).prop("checked", true);
                                }
                            }
                        });
                    });
                })
            } else {
                toastr.error(res.message);
            }
            parent.HideAzLoading();
        },
        error: function (err) {
            console.log(err);
            parent.HideAzLoading();
            toastr.error("服务器发生错误，请稍候再试An error occurred in the server. Please try again later。");
        }
    });
}

/**
 * 重置用户角色关系信息
 */
function ResetUserRoleMapping(vue) {
    if (vue.user != null) {
        vue.user.UserRoleMappings = [];
        $("#userRoleDetail").find("input[type=checkbox]").each(function () {
            if ($(this).prop("checked") == true) {
                var mapping = {
                    RoleID: $(this).val(),
                    UserID: vue.user.ID
                }
                vue.user.UserRoleMappings.push(mapping);
            }
        });
    }
}

/**
 * 列出所有用户权限信息
 */
function ListAllPermission(vue) {
    parent.ShowAzLoading();
    $.ajax({
        type: "GET",
        url: "/Account/ListPermission?v=" + Math.random(),
        success: function (res) {
            if (res.status == "Success") {
                vue.permissionList = res.data;

                vue.$nextTick(function () {
                    //监听Bootstrap中Tab元素显示事件
                    $('a[data-toggle="tab"]').off('shown.bs.tab').on('shown.bs.tab', function (e) {
                        parent.ResizeAzModal();
                        //选中已有权限关系记录
                        $("#userPermissionDetail").find("input[type=checkbox]").each(function () {
                            for (var idx in vue.user.UserPermissionMappings) {
                                if (vue.user.UserPermissionMappings[idx].PermissionID == $(this).val()) {
                                    $(this).prop("checked", true);
                                }
                            }
                        });
                    });
                })
            } else {
                toastr.error(res.message);
            }
            parent.HideAzLoading();
        },
        error: function (err) {
            console.log(err);
            parent.HideAzLoading();
            toastr.error("服务器发生错误，请稍候再试An error occurred in the server. Please try again later。");
        }
    });
}

/**
 * 重置用户权限关系信息
 */
function ResetUserPermissionMapping(vue) {
    if (vue.user != null) {
        vue.user.UserPermissionMappings = [];
        $("#userPermissionDetail").find("input[type=checkbox]").each(function () {
            if ($(this).prop("checked") == true) {
                var mapping = {
                    PermissionID: $(this).val(),
                    UserID: vue.user.ID
                }
                vue.user.UserPermissionMappings.push(mapping);
            }
        });
    }
}
